﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Globalization;
using Ankin.EHBH.CommonUtil.Util;

namespace Ankin.EHBH.Web.Controls
{
    public partial class wucFileUpload : System.Web.UI.UserControl
    {
        Ankin.EHBH.BLL.BllLicense bllLicense = new Ankin.EHBH.BLL.BllLicense();
        string mstrFilePath = "attachment";
        string mstrLicenseid = string.Empty;
        int type = 0;
        string sellno = string.Empty;
        override protected void OnInit(EventArgs e)
        {

            InitializeComponent();
            base.OnInit(e);

        }
        private void InitializeComponent()
        {
            //this.grdList.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.grdList_ItemCreated);
            this.grdList.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.grdList_ItemCommand);
            // this.grdList.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.grdList_PageIndexChanged);
            // this.grdList.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.grdList_SortCommand);
            this.grdList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.grdList_ItemDataBound);

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SaveCurrentPageFileControls();
                DataBind();
            }
        }
        /// <summary>
        /// datagrid数据绑定
        /// </summary>
        private void DataBind()
        {
            DataSet dsAttach = bllLicense.GetLicenseAttach("license_id='" + LicenseID + "'");
            grdList.DataSource = dsAttach;
            grdList.DataBind();
        }
        #region DataGrid操作方法
        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdList_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            // 删除附件		
            if (e.CommandName.ToLower() == "imgdel")
            {
                // 获取文件ID	
                string strFileID = e.Item.Cells[0].Text;

                string strPath = e.Item.Cells[2].Text;
                // 删除选中的行记录
                bllLicense.DeleteAttach(LicenseID, strFileID, strPath);
                File.Delete(strPath + "\\" + strFileID);
                DataBind();


            }
            // 下载附件
            if ((e.CommandName.ToLower() == "downfile"))
            {
                // 获取文件路径					
                string strFilePath = e.Item.Cells[2].Text;
                // 获取文件物理文件名	
                string strFileName = e.Item.Cells[0].Text;
                // 文件路径			
                string strFileallPath = strFilePath + "\\" + strFileName;
                //LinkButton lbtnDescr = (LinkButton)e.Item.Cells[3].FindControl("lbtnDescr");

                //// 文件名
                //string strFileDescr =
                //  lbtnDescr.Text.Replace("<img  src=\"~/images/Down_Arrow.gif border=\"0\" align=\"absmiddle\" /> ", "");

                //// 文件名太长截取掉
                //if (strFileDescr.Length > 12)
                //{
                //    strFileDescr = strFileDescr.Substring(0, 10) + "...";
                //}

                // 下载文件	
                if (!FileDownload(this.Response, strFileallPath, strFileName.Substring(0, strFileName.LastIndexOf("."))))
                {
                    //下载不成功，“文件不存在！”
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "error", "<script language=javascript>alert('文件不存在！');</script>");
                    return;
                }
            }

        }


        /// <summary>
        /// 网格行绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)
                || (e.Item.ItemType == ListItemType.EditItem))
            {
                // 查找删除按钮
                ImageButton btnDel = (ImageButton)e.Item.Cells[6].FindControl("btnDel");
                // 文件路径			
                string strFilePath = e.Item.Cells[2].Text;
                // 文件扩展名
                string strExtensionName = Path.GetExtension(strFilePath);
                LinkButton lbtnDescr = (LinkButton)e.Item.Cells[3].FindControl("lbtnDescr");
                // 文件描述	
                string strFileName = lbtnDescr.Text + strExtensionName;
                //“删除”
                btnDel.ToolTip = "删除";

                //// 如果在view页面则不显示删除列
                //if (this.UrlAction == Enums.EUrlAction.View || this.UrlAction == Enums.EUrlAction.Audit)
                //{
                //    this.grdList.Columns[6].Visible = false;
                //}

                // 删除按钮添加客户端事件111, 你确定要删除“1%”吗？
                btnDel.Attributes.Add("onclick", "return confirm('你确定要删除此文件吗？');");
                // 查找下载链接按钮
                LinkButton lbtnDown = (LinkButton)e.Item.Cells[3].FindControl("lbtnDescr");
                lbtnDown.CssClass = "ContentLink";
                lbtnDown.Text = "<img  src=\"~/images/Down_Arrow.gif border=\"0\" align=\"absmiddle\" /> " + lbtnDown.Text;
                // "点击立即下载！"
                lbtnDown.ToolTip = "点击立即下载！";


                // 判断权限,如果不是作者或超级管理员用户不可删除
                //if ((e.Item.Cells[1].Text.Trim().ToLower() != this.SessionInfo.UserID.ToLower()) &&
                //    (this.GetGlobalParaValue(101).Trim().ToLower() != this.SessionInfo.UserID.ToLower()))
                //{
                //    btnDel.Visible = false;
                //}
                // 设置时间格式
                e.Item.Cells[5].Text = ShowSDPDateTime(Convert.ToDateTime(e.Item.Cells[5].Text));
                //Common.ShowSDPDateTime(Convert.ToDateTime(e.Item.Cells[5].Text), true);
                // Common.SetGridItemHighlight(e.Item);
            }
        }

        #endregion
        public static string ShowSDPDateTime(DateTime dtmInput)
        {
            string strReturn = "";
            if (dtmInput.ToString("yyyy-MM-dd") == "1900-01-01")
            {
                return strReturn;
            }

            strReturn = dtmInput.ToString("yyyy-MM-dd hh:mm", DateTimeFormatInfo.InvariantInfo);
            return strReturn;
        }
        protected void btAddFile_Click(object sender, EventArgs e)
        {
            AddOneFileControl();
        }

        /// <summary>
        /// 添加一个上传文件控件
        /// </summary>
        private void AddOneFileControl()
        {
            ArrayList al = new ArrayList();
            this.tbFiles.Rows.Clear();
            GetFileControlsFromSession();
            HtmlTableRow htr = new HtmlTableRow();
            FileUpload fileupLoad = new FileUpload();
            fileupLoad.CssClass = "fileupload";
            //fileupLoad.Width = "95%";
            HtmlTableCell htc0 = new HtmlTableCell();
            Label lbl = new Label();
            lbl.Text = "附件";
            htc0.Controls.Add(lbl);
            HtmlTableCell htc = new HtmlTableCell();
            System.Web.UI.WebControls.Button btn = new Button();
            btn.ID = "btAddFile";
            btn.Text = "增加文件";
            btn.Click += new EventHandler(btAddFile_Click);
            HtmlTableCell htc1 = new HtmlTableCell();
            htc1.Controls.Add(btn);
            htc.Controls.Add(fileupLoad);
            htr.Controls.Add(htc0);
            htr.Controls.Add(htc);
            htr.Controls.Add(htc1);
            this.tbFiles.Rows.Add(htr);
            //SpaceRow();
            SaveCurrentPageFileControls();
        }

        public void SpaceRow()
        {

            // 创建附件说明行对象
            HtmlTableRow objRemarkRow = new HtmlTableRow();
            // 定义附件说明标签单元格对象		
            HtmlTableCell objRemarkCellLabel = new HtmlTableCell();
            // 定义附件说明Label对象 				
            Label lblRemark = new Label();
            lblRemark.Text = "说明:";
            // 设置单元格样式	
            //objRemarkCellLabel. = "ViewTitle";
            // 设置单元格内不换			
            //objRemarkCellLabel. = true;
            // 把标签添加到单元格中			
            objRemarkCellLabel.Controls.Add(lblRemark);

            // 把单元格添加到附件说明行对象中							
            objRemarkRow.Cells.Add(objRemarkCellLabel);
            // 定义附件说明编辑单元格对象		
            HtmlTableCell objRemarkCellEdit = new HtmlTableCell();
            // 定义附件说明TextBox对象		
            TextBox txtRemarkValue = new TextBox();
            // 初始附件说明文本框属性							
            txtRemarkValue.Text = "";
            // 设置文本框宽度			
            txtRemarkValue.Style.Add("Width", "100%");
            // 设置单元格样式	
            //objRemarkCellEdit.CssClass = "EditorBody";
            // 把附件说明文本框添加到单元格中	
            objRemarkCellEdit.Controls.Add(txtRemarkValue);
            // 把单元格添加到行对象中	
            objRemarkRow.Cells.Add(objRemarkCellEdit);
            // 把附件说明行对象添加表格中
            tbFiles.Rows.Add(objRemarkRow);
        }

        /// <summary>
        /// 读取缓存中存储的上传文件控件集
        /// </summary>
        private void GetFileControlsFromSession()
        {
            ArrayList al = new ArrayList();
            if (Session["FilesControls"] != null)
            {
                al = (System.Collections.ArrayList)Session["FilesControls"];
                for (int i = 0; i < al.Count; i++)
                {
                    HtmlTableRow htr1 = new HtmlTableRow();
                    HtmlTableCell htc0 = new HtmlTableCell();
                    Label lbl = new Label();
                    lbl.Text = "附件";
                    htc0.Controls.Add(lbl);
                    HtmlTableCell htc1 = new HtmlTableCell();
                    HtmlTableCell htc2 = new HtmlTableCell();
                    htc1.Controls.Add((System.Web.UI.WebControls.FileUpload)al[i]);
                    htr1.Controls.Add(htc0);
                    htr1.Controls.Add(htc1);
                    htc1.Controls.Add(htc2);
                    this.tbFiles.Rows.Add(htr1);
                    //SpaceRow();
                }
            }
        }

        /// <summary>
        /// 保存当前页面上传文件控件集到缓存中
        /// </summary>    
        private void SaveCurrentPageFileControls()
        {
            ArrayList al = new ArrayList();
            foreach (Control controlTR in this.tbFiles.Controls)
            {
                if (controlTR.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlTableRow")
                {
                    HtmlTableCell htc = (HtmlTableCell)controlTR.Controls[1];
                    foreach (Control controlFileUpload in htc.Controls)
                    {
                        if (controlFileUpload.GetType().ToString() == "System.Web.UI.WebControls.FileUpload")
                        {
                            FileUpload tempFileUpload = (FileUpload)controlFileUpload;
                            al.Add(tempFileUpload);
                        }
                    }
                }
            }
            Session.Add("FilesControls", al);
        }

        protected void btUpFiles_Click(object sender, EventArgs e)
        {
            UpLoadFiles();
            DataBind();
        }
        /// <summary>
        /// 公用上传方法
        /// </summary>
        public void UpLoad()
        {
            UpLoadFiles();
            DataBind();
        }

        /// <summary>
        /// 上传文件操作
        /// </summary>
        private void UpLoadFiles()
        {
            string filepath = Server.MapPath("~") + "UpLoad";
            if (Type == 1)//如果是factory类型
            {
                filepath += "\\factory\\" + SellNo;
            }
            else
                filepath += "\\sell\\" + SellNo;

            //   判断上传文件夹是否存在 
            if (!System.IO.Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
            HttpFileCollection uploadedFiles = Request.Files;
            Ankin.EHBH.Model.ModelEXP_LICENSE_ATTACH modeAttach = new Ankin.EHBH.Model.ModelEXP_LICENSE_ATTACH();
            for (int i = 0; i < uploadedFiles.Count; i++)
            {
                HttpPostedFile userPostedFile = uploadedFiles[i];
                try
                {
                    if (userPostedFile.ContentLength > 0)
                    {
                        userPostedFile.SaveAs(filepath + "\\" + System.IO.Path.GetFileName(userPostedFile.FileName));

                        modeAttach.LICENSE_ID = LicenseID;
                        modeAttach.FILE_NAME = System.IO.Path.GetFileName(userPostedFile.FileName);
                        modeAttach.UPLOAD_MAN = Session[EHBHConstant.SESSION_USERID].ToString();
                        modeAttach.PATH = filepath;
                        // modeAttach.DESCR = text1.Text;
                        bllLicense.AddAttach(modeAttach);
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ok", "<script language=javascript>alert('上传成功！');</script>");
                        // Response.Write("已上传文件: \"" + filepath + "\\" + userPostedFile.FileName + "\"<br><br>");

                    }
                }
                catch
                {
                    Response.Write("上传文件: \"" + userPostedFile.FileName + "\"出错!");
                }
            }
            if (Session["FilesControls"] != null)
            {
                Session.Remove("FilesControls");
            }
        }
        #region 属性
        /// <summary>
        /// 设置LicenseID号码
        /// </summary>
        public string LicenseID
        {
            get
            {
                if (ViewState["mstrLicenseid"] == null)
                    return "";
                else
                    return ViewState["mstrLicenseid"].ToString();
            }
            set
            {
                ViewState["mstrLicenseid"] = value;
            }
        }
        /// <summary>
        /// 资质所属类型 0-sell；1-factory
        /// </summary>
        public int Type
        {
            get
            {

                if (string.IsNullOrEmpty(ViewState["type"].ToString()))
                    return 0;
                else
                    return Convert.ToInt16(ViewState["type"]);
            }
            set
            {
                ViewState["type"] = value;
            }

        }
        /// <summary>
        /// 销售商代码
        /// </summary>
        public string SellNo
        {
            get
            {
                if (string.IsNullOrEmpty(ViewState["sellno"].ToString()))
                    return "";
                else
                    return ViewState["sellno"].ToString();
            }
            set
            {
                ViewState["sellno"] = value;
            }
        }

        #endregion

        #region 文件下载
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="response">Response对象</param>
        /// <param name="strFile">欲下载绝对全路径文件名</param>
        /// <param name="strNewFile">客户端目标文件名（未带扩展名）</param>
        public static bool FileDownload(System.Web.HttpResponse response, string strFile, string strNewFile)
        {
            if (!System.IO.File.Exists(strFile))
            {
                return false;
            }

            System.IO.Stream iStream = null;

            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[1024 * 8];

            // Length of the file:
            int length;

            // Total bytes to read:
            long dataToRead;

            // Identify the file to download including its path.
            string filepath = strFile;

            // Identify the file name.
            string filename = System.IO.Path.GetFileName(filepath);

            try
            {

                response.Clear();
                response.ClearHeaders();
                response.Charset = "utf-8";
                response.ContentEncoding = System.Text.UTF8Encoding.UTF8;  //System.Text.Encoding.UTF8 ;
                response.ContentType = "application/octet-stream";
                FileInfo fi = new FileInfo(strFile);
                strNewFile = strNewFile + fi.Extension;
                string strRealFile = HttpUtility.UrlEncode(strNewFile, System.Text.Encoding.UTF8);
                //因为文件名中的空格被转为+，所以这里要再转回去。(只对空格作了转换，要知道文件名的命名规范？)
                strRealFile = strRealFile.Replace("+", " ");
                response.AddHeader("Content-Disposition", "attachment;  filename = " + strRealFile);
                response.AddHeader("Content-Length", fi.Length.ToString());

                // Open the file.
                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                            System.IO.FileAccess.Read, System.IO.FileShare.Read);


                // Total bytes to read:
                dataToRead = iStream.Length;

                // Read the bytes.
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, buffer.Length);

                        // Write the data to the current output stream.
                        response.OutputStream.Write(buffer, 0, length);
                        //response.BinaryWrite(buffer);

                        // Flush the data to the HTML output.
                        response.Flush();

                        buffer = new Byte[1024 * 8];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
                response.End();
            }

            return true;

        }
        #endregion
    }
}